<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import draggable from 'vuedraggable'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const form = reactive({
  tabId: 0,
  tabName: 'market_marryattrib',
  // ----
  id: 0,
  name: ''
})
// ----
let globalData = {}
// ----
const dragOptions = {
  handle: '.mover',
  animation: 300,
  itemKey: 'id'
}
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
// --getData--
const getListData = async (callback) => {
  const newItems = forSys.filter((item) => { return String(item.name) === form.tabName })
  if (Number(newItems.length) === 1) {
    form.tabId = newItems[0].id
    await proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      globalData = resJson[0]
      // ----
      if (resJson[0].list) items.value = resJson[0].list
    })
  }
  // ----
  callback && callback()
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const setSortNum = async () => {
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  // ----
  globalData.list = items.value
  // ----
  const forValue = JSON.stringify(globalData)
  // ----
  await proxy.$http.patch('system/update?id=' + form.tabId, {
    value: forValue,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
}
// ----
const checkInfoDel = async (item) => {
  let newItems = []
  const forSch = ',' + item.id + ','
  await proxy.$http.get('marriage-frm/index', {
    params: { 'MarriageFrmSearch[type]': forSch }
  }).then((res) => { newItems = res.items }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(newItems.length) > 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '该属性已使用，不能删除')
    return false
  }
  // ----
  const options = {
    content: proxy.$Global.layer.conDel,
    button: [{
      text: proxy.$Global.layer.btnCancel
    }, {
      text: proxy.$Global.layer.btnDel,
      class: 'xw-color-24',
      callback: () => {
        layerBox.value.close()
        // ----
        items.value.some((curItem, index) => {
          if (Number(curItem.id) === Number(item.id)) items.value.splice(index, 1)
        })
        // ----
        globalData.list = items.value
        // ----
        const forValue = JSON.stringify(globalData)
        // ----
        proxy.$http.patch('system/update?id=' + form.tabId, {
          value: forValue,
          // ----
          config_id: userInfo.config_id,
          openid: userInfo.openid
        }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      }
    }]
  }
  proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
  // ----
  getAuditFun(4)
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      if (Number(form.name.length) === 0) getAuditFun(4)
      break
    }
    case 2: {
      form.id = item.id
      form.name = item.name
      break
    }
    case 3: {
      checkInfoDel(item)
      break
    }
    case 4: {
      form.id = 0
      form.name = ''
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写交友属性！')
    return false
  }
  // ----
  if (Number(form.id) > 0) {
    items.value.some((item, index) => {
      if (Number(item.id) === Number(form.id)) item.name = form.name
    })
  } else {
    globalData.maxId = Number(globalData.maxId) > 0 ? Number(globalData.maxId) + 1 : 1
    items.value.push({
      id: globalData.maxId,
      name: form.name
    })
  }
  // ----
  globalData.list = items.value
  // ----
  const forValue = JSON.stringify(globalData)
  // ----
  let forType = 'post'
  let forUrl = 'system/create'
  let forData = {
    name: form.tabName,
    value: forValue,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (Number(form.tabId) > 0) {
    forType = 'patch'
    forUrl = 'system/update?id=' + form.tabId
    forData = {
      value: forValue,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  await proxy.$http[forType](forUrl, forData).then((res) => {
    if (Number(form.tabId) === 0 && res) form.tabId = res.id
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  // ----
  getAuditFun(4)
}

/* ---- */
onMounted(() => {
  getListData(() => {
    proxy.$Myfun.setDragMargin()
  })
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <p class="xw-flex-W1"><input class="text" type="text" placeholder="填写交友属性" v-model.trim="form.name" @blur="getAuditFun(1)"/></p>
          <transition name="fade"><em class="TOP-R fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
        </div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="subform">提交</span>
      </div>
    </header>
    <div class="xw-drag">
      <div class="mescroll-empty" v-if="Number(items.length) === 0"><p class="empty-tip">{{$Global.noData}}</p></div>
      <draggable tag="ul" v-model="items" v-bind="dragOptions" @end="setSortNum" class="list-class xw-flex xw-flex-column" v-else>
        <template #item="{element, index}">
          <li class="xw-Tfg xw-bg-white xw-flex">
            <div class="LCS-title xw-ellipsis xw-flex-W1 xw-flex xw-flex-align">{{element.name}}</div>
            <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(2, element)"><em class="fa fa-edit"></em>修改</div>
            <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(3, element)"><em class="fa fa-trash-alt"></em>删除</div>
            <span class="mover LCS-drag xw-act fa fa-bars xw-flex xw-flex-center"></span>
          </li>
        </template>
      </draggable>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.TOP-submit { margin-left: 1rem; }

/* ---- */
.list-class li { padding: 0 1rem; }
.list-class li:before { left: 1rem; }
.list-class li:nth-of-type(1):before { display: none; }
.LCS-title { font-size: 1.6rem; }
.LCS-btn { margin: 0 0 0 1.2rem; padding: 1.4rem 0; }
.LCS-btn em { margin-right: 0.5rem; color: #aaaaaa; }
.LCS-drag { margin-right: -1.2rem; padding: 0 1.2rem; font-size: 2rem; }

/* ---- */
.sortable-chosen { background: #3388ff; color: #ffffff; }
.sortable-chosen .LCS-btn em { color: #ffffff; }
</style>
